/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.robert.maps;

import java.util.ArrayList;
import java.util.List;

import org.andnav.osm.util.GeoPoint;
import org.andnav.osm.views.util.Util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.Instrumentation.ActivityResult;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.robert.maps.R;
import com.robert.maps.utils.POI;
import com.robert.maps.utils.KmlPullParser;

/**
 * This example shows how to use choice mode on a list. This list is 
 * in CHOICE_MODE_MULTIPLE mode, which means the items behave like
 * checkboxes.
 */
public class POIList extends Activity {
    
	private SQLiteDatabase mPOI;
	private ListView listView;
	private ArrayList<String> aPOIName;
	private ArrayList<String> aPOIGeoPoint;
	private ArrayList<String> aPOICategory;
	private ArrayList<String> aPOIID;
	private SparseBooleanArray sA;
	private ArrayAdapter<String> aPOIArray;
	
	private Spinner poiCategory;
	private boolean bSpinnerInitializing = true;
	
	private static final int DIALOG_DeleteSelected = 1;
	private static final int DIALOG_DeleteCategory = 2;
	private static final int DIALOG_DeleteAll = 3;
	private static final int DIALOG_CategoryList = 4;	
	
	private String newCategory="Others";
	private boolean changeAllCategory;
	private ArrayAdapter<CharSequence> CatetoryAdapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View v = View.inflate(this, R.layout.poilist , null);
        setContentView(v);
        aPOIName = new ArrayList<String>();
        aPOIGeoPoint = new ArrayList<String>();
        aPOICategory = new ArrayList<String>();
        aPOIID = new ArrayList<String>();
		//set poi category
		poiCategory = (Spinner) v.findViewById(R.id.Spinner01);
		CatetoryAdapter = ArrayAdapter.createFromResource(this, R.array.poi_category2,
                android.R.layout.simple_spinner_item);
		CatetoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        poiCategory.setAdapter(CatetoryAdapter);
        poiCategory.setOnItemSelectedListener(selectListener); 
        
        //joeng POI
    	if (mPOI == null)
    	{
    		this.mPOI= Util.getPOIDatabase(false);
    	}
    	listView = (ListView) v.findViewById(R.id.ListView01);
		buildPOIListView("All");
    }

    private OnItemSelectedListener selectListener = new OnItemSelectedListener() 
    {
        public void onItemSelected(AdapterView parent, View v, int position, long id) 
        {
        	if (!bSpinnerInitializing){
        		buildPOIListView((String)poiCategory.getItemAtPosition(position));
        	}
        	else
        		bSpinnerInitializing = false;
        }
        public void onNothingSelected(AdapterView arg0) 
        {
          
        }
    };
    
   
	private void buildPOIListView(String category) {
		final Cursor c;
		Integer iCount=0;
		if (category.equalsIgnoreCase("all")){
			//c = this.mPOI.rawQuery("Select name,latitude,longitude, category from PlacesInfo order by name", null);
			c = this.mPOI.rawQuery("SELECT a.name, b.latitude,b.longitude, a.category, a.PlaceID FROM PlacesInfo a inner join " +
					"PlacesGeoPoint b on a.PlaceID = b.PlaceID order by a.name", null);
		}
		else if (category.equalsIgnoreCase("all shown")){
			//c = this.mPOI.rawQuery("Select name,latitude,longitude, category from PlacesInfo where show = 1 order by name", null);
			c = this.mPOI.rawQuery("SELECT a.name, b.latitude,b.longitude, a.category, a.PlaceID FROM PlacesInfo a inner join " +
					"PlacesGeoPoint b on a.PlaceID = b.PlaceID where a.show = 1 order by a.name", null);
		}
		else if (category.equalsIgnoreCase("all hidden")){
			//c = this.mPOI.rawQuery("Select name,latitude,longitude, category from PlacesInfo where show = 0 order by name", null);
			c = this.mPOI.rawQuery("SELECT a.name, b.latitude,b.longitude, a.category, a.PlaceID FROM PlacesInfo a inner join " +
					"PlacesGeoPoint b on a.PlaceID = b.PlaceID where a.show = 0 order by a.name", null);
		}
		else{
			//c = this.mPOI.rawQuery("Select name,latitude,longitude, category from PlacesInfo where category = '" + category + "' order by name", null);
			c = this.mPOI.rawQuery("SELECT a.name, b.latitude,b.longitude, a.category, a.PlaceID FROM PlacesInfo a inner join " +
					"PlacesGeoPoint b on a.PlaceID = b.PlaceID where a.category = '" + category + "' order by a.name", null);
		}
		
		aPOIName.clear();
		aPOIGeoPoint.clear();
		aPOICategory.clear();
		aPOIID.clear();
		if (c.moveToFirst()) {
			do {
				if (aPOIID.size() == 0 || !aPOIID.get(iCount-1).equalsIgnoreCase(c.getString(4))){
					aPOIName.add(c.getString(0)) ;
					aPOIGeoPoint.add(c.getString(1)+","+c.getString(2));
					aPOICategory.add(c.getString(3));
					aPOIID.add(c.getString(4));
					iCount++;
				}
			} while (c.moveToNext());
		}
		c.close();
		aPOIArray = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice, aPOIName);

        listView.setAdapter(aPOIArray);
        listView.setItemsCanFocus(false);
        listView.setTextFilterEnabled(true);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener 
                (){ 
                	public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
                		showEditPOIDialog(POIList.this,aPOIID.get(pos), aPOIName.get(pos), 
								aPOICategory.get(pos), pos);
                		return true; 
                } 
                }); 
	}

	
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.poi_list_option_menu, menu);

		return true;
	}

    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		

		if (sA != null){sA = null;}
		
		if (listView!= null && listView.getCount()>0) {
			sA = listView.getCheckedItemPositions();
		}
		
		switch (item.getItemId()) {
		//joeng POI
		case (R.id.list_manage):
			showManagePOIDialog(this);
			return true;
		case (R.id.list_import):
			try{
				startActivityForResult(new Intent(this, KmlList.class),30000);
			}
			catch (Exception e){
				String cec= e.toString();
			}
			return true;
		case (R.id.list_GoTo):
			if (sA!=null){
				for (int i = 0; i < sA.size(); i++) {
					try{
						if (sA.get(sA.keyAt(i))){
							setResult(20003,new Intent(aPOIGeoPoint.get(sA.keyAt(i))));
							break;
						}
					}
					catch (Exception e){
						String abc = e.toString();
					}
				}
				finish();
			}
			return true;
		}
		return true;
    }

    private void showManagePOIDialog(final Context context) {
		View v = View.inflate(context, R.layout.managepoi , null);
		final AlertDialog dialog = new AlertDialog.Builder(context).create();
		dialog.setView(v);
		dialog.setTitle("Manage POI");
		
		final Button editBtn = (Button) v.findViewById(R.id.editselectedBtn);
		editBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ManaePOI(R.id.editselectedBtn);
				dialog.dismiss();
			}
		});
		
		final Button showselectedBtn = (Button) v.findViewById(R.id.showselectedBtn);
		showselectedBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ManaePOI(R.id.showselectedBtn);
				dialog.dismiss();
			}
		});
		
		final Button showallBtn = (Button) v.findViewById(R.id.showallBtn);
		showallBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ManaePOI(R.id.showallBtn);
				dialog.dismiss();
			}
		});
		
		final Button hideselectedBtn = (Button) v.findViewById(R.id.hideselectedBtn);
		hideselectedBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ManaePOI(R.id.hideselectedBtn);
				dialog.dismiss();
			}
		});
		
		final Button hideallBtn = (Button) v.findViewById(R.id.hideallBtn);
		hideallBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ManaePOI(R.id.hideallBtn);
				dialog.dismiss();
			}
		});
		
		final Button deleteselectedBtn = (Button) v.findViewById(R.id.deleteselectedBtn);
		deleteselectedBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ManaePOI(R.id.deleteselectedBtn);
				dialog.dismiss();
			}
		});
		
		final Button deleteallBtn = (Button) v.findViewById(R.id.deleteallBtn);
		deleteallBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ManaePOI(R.id.deleteallBtn);
				dialog.dismiss();
			}
		});
		
		final Button categorizeselectedBtn = (Button) v.findViewById(R.id.categoryselectedBtn);
		categorizeselectedBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ManaePOI(R.id.categoryselectedBtn);
				dialog.dismiss();
			}
		});
		
		final Button categorizeallBtn = (Button) v.findViewById(R.id.categoryallBtn);
		categorizeallBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ManaePOI(R.id.categoryallBtn);
				dialog.dismiss();
			}
		});
		dialog.show();
		
		final Button cityselectedBtn = (Button) v.findViewById(R.id.cityselectedBtn);
		cityselectedBtn.setVisibility(View.GONE);
		final Button cityallBtn = (Button) v.findViewById(R.id.cityallBtn);
		cityallBtn.setVisibility(View.GONE);
    }
    
	public boolean ManaePOI(Integer item) {
		switch (item) {
		//joeng POI
		case (R.id.editselectedBtn):
			if (sA!=null){
				for (int i = 0; i < sA.size(); i++) {
					try{
						if (sA.get(sA.keyAt(i))){
							showEditPOIDialog(this, aPOIID.get(sA.keyAt(i)), aPOIName.get(sA.keyAt(i)), 
									aPOICategory.get(sA.keyAt(i)), sA.keyAt(i));
							break;
						}
					}
					catch (Exception e){
						String abc = e.toString();
					}
				}
			}
			return true;
		case (R.id.deleteselectedBtn): // delete selected POI
			showDialog(DIALOG_DeleteSelected);
			return true;
		case (R.id.deleteallBtn): // delete all POI
			if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("All"))
				showDialog(DIALOG_DeleteAll);
			else
				showDialog(DIALOG_DeleteCategory);
			return true;			
		case (R.id.showselectedBtn): //show selected POI
			if (sA!=null){
//				if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("All"))
//					this.mPOI.execSQL("Update PlacesInfo set show = 0 ;");
//				else 
//					this.mPOI.execSQL("Update PlacesInfo set show = 0 where category = '" + (String)poiCategory.getSelectedItem() + "';");
				for (int i = 0; i < sA.size(); i++) {
					if (sA.get(sA.keyAt(i))){
						this.mPOI.execSQL("Update PlacesInfo set show = 1 where name ='" + aPOIName.get(sA.keyAt(i)).replace("'", "''") + "'" +
								" and category = '" + aPOICategory.get(sA.keyAt(i)) + "';");
					}
				}

//				for (int i = 0; i < aPOIName.size(); i++) {
//					if (sA.get(i)){
//						this.mPOI.execSQL("Update PlacesInfo set show = 1 where name ='" + aPOIName.get(i).replace("'", "''") + "'" +
//								" and Category = '" + aPOICategory.get(i) + "';");	
//					}
//				}
				setResult(20002);
			}
			return true;
		case (R.id.showallBtn): //show all POI
			if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("All"))
				this.mPOI.execSQL("Update PlacesInfo set show = 1 ;");
			else if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("all shown")){
				//this.mPOI.execSQL("Update PlacesInfo set show = 1 ;");
				//do nothing
			}
			else if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("all hidden"))
				this.mPOI.execSQL("Update PlacesInfo set show = 1 where show = 0 ;");
			else
				this.mPOI.execSQL("Update PlacesInfo set show = 1 where category = '" + (String)poiCategory.getSelectedItem() + "';");
			setResult(20002);
			return true;
		case (R.id.hideselectedBtn): //hide selected POI
			if (sA!=null){
//				if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("All"))
//					this.mPOI.execSQL("Update PlacesInfo set show = 1 ;");
//				else
//					this.mPOI.execSQL("Update PlacesInfo set show = 1 where category = '" + (String)poiCategory.getSelectedItem() + "';");
				for (int i = 0; i < sA.size(); i++) {
						if (sA.get(sA.keyAt(i))){
							this.mPOI.execSQL("Update PlacesInfo set show = 0 where name ='" + aPOIName.get(sA.keyAt(i)).replace("'", "''") + "'" +
									" and category = '" + aPOICategory.get(sA.keyAt(i)) + "';");
						}
				}
						
//				for (int i = 0; i < aPOIName.size(); i++) {
//					if (sA.get(i)){
//						this.mPOI.execSQL("Update PlacesInfo set show = 0 where name ='" + aPOIName.get(i).replace("'", "''") + "';");	
//					}
//				}
				
				setResult(20002);
			}
			return true;
		case (R.id.hideallBtn): //hide all POI
			if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("All"))
				this.mPOI.execSQL("Update PlacesInfo set show = 0 ;");
			else if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("all shown"))
				this.mPOI.execSQL("Update PlacesInfo set show = 0 where show = 1 ;");
			else if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("all hidden")){
				//do nothing
			}
			else
				this.mPOI.execSQL("Update PlacesInfo set show = 0 where category = '" + (String)poiCategory.getSelectedItem() + "';");
			setResult(20002);
			return true;
		case (R.id.categoryselectedBtn):
			changeAllCategory = false;
			showDialog(DIALOG_CategoryList);
			return true;
		case (R.id.categoryallBtn):
			changeAllCategory = true;
			showDialog(DIALOG_CategoryList);
			return true;
		}
		return true;
    }
	
    private void ChangeCategory(String newCategory){
    	if (!changeAllCategory){
			if (sA!=null){
				for (int i = 0; i < aPOIName.size(); i++) {
					if (sA.get(i)){
						this.mPOI.execSQL("Update PlacesInfo set category = '" + newCategory + "' " +
								"where name ='" + aPOIName.get(i).replace("'", "''") + "'" +
								" and category = '" + aPOICategory.get(i) + "';");
						aPOICategory.set(i, newCategory);	
					}
				}
			}
    	}
    	else{
			if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("All"))
				this.mPOI.execSQL("Update PlacesInfo set category = '" + newCategory + "' ;");
			else if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("all shown"))
				this.mPOI.execSQL("Update PlacesInfo set category = '" + newCategory + "' " +
						"where show = 1;");
			else if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("all hidden"))
				this.mPOI.execSQL("Update PlacesInfo set category = '" + newCategory + "' " +
						"where show = 0;");
			else 
				this.mPOI.execSQL("Update PlacesInfo set category = '" + newCategory + "' " +
						"where category = '" + (String)poiCategory.getSelectedItem() + "';");
			for (int i = 0; i < aPOIName.size(); i++) {
				aPOICategory.set(i, newCategory);
			}
    	}
    	setResult(20006);
    }

    private void SetNewCategory(String NewCategory){
    	newCategory = NewCategory;
    }
    
    private void DeletePOI(String POIID, Integer RecordPos) {
		this.mPOI.delete("PlacesInfo", "PlaceID = '" + POIID +"'" , null);
		this.mPOI.delete("PlacesGeoPoint", "PlaceID = '" + POIID + "'" , null);
		aPOIArray.remove(aPOIName.get(RecordPos));
		aPOIName.remove(RecordPos);;
		aPOIGeoPoint.remove(RecordPos);
		aPOICategory.remove(RecordPos);;
		aPOIID.remove(RecordPos);
		listView.clearChoices();
    }
	private void DeletePOI(boolean DeleteAll) {
		Integer iDelCount=0;
		if (!DeleteAll){
			if (sA!=null){
				for (int i = 0; i < sA.size(); i++) {
					try{
						if (sA.get(sA.keyAt(i))){
							this.mPOI.delete("PlacesInfo", "name = '" + aPOIName.get(sA.keyAt(i)-iDelCount).replace("'", "''") + "'" +
									" and Category = '" + aPOICategory.get(sA.keyAt(i)-iDelCount) + "'" , null);
							this.mPOI.delete("PlacesGeoPoint", "PlaceID = '" + aPOIID.get(sA.keyAt(i)-iDelCount) + "'" , null);
							aPOIArray.remove(aPOIName.get(sA.keyAt(i)-iDelCount));
							aPOIName.remove(sA.keyAt(i)-iDelCount);;
							aPOIGeoPoint.remove(sA.keyAt(i)-iDelCount);
							aPOICategory.remove(sA.keyAt(i)-iDelCount);;
							aPOIID.remove(sA.keyAt(i)-iDelCount);
							iDelCount++;
						}
					}
					catch (Exception e){
						String abc = e.toString();
					}
				}
				listView.clearChoices();
				setResult(20001);
			}
		}
		else{
			if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("All")){
				this.mPOI.delete("PlacesInfo", null, null);
				this.mPOI.delete("PlacesGeoPoint", null, null);
			}
			else if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("all shown")){
				this.mPOI.delete("PlacesGeoPoint", "PlacesGeoPoint.PlaceID in " +
						"(SELECT PlaceID FROM PlacesInfo where show = 1)", null);
				this.mPOI.delete("PlacesInfo", "show = 1", null);
			}
			else if (((String)poiCategory.getSelectedItem()).equalsIgnoreCase("all hidden")){
				this.mPOI.delete("PlacesGeoPoint", "PlacesGeoPoint.PlaceID in " +
						"(SELECT PlaceID FROM PlacesInfo where show = 0)", null);
				this.mPOI.delete("PlacesInfo", "show = 0", null);
			}
			else{
				this.mPOI.delete("PlacesGeoPoint", "PlacesGeoPoint.PlaceID in " +
						"(SELECT PlaceID FROM PlacesInfo where category = '" + (String)poiCategory.getSelectedItem() + "')", null);
				this.mPOI.delete("PlacesInfo", "category = '" + (String)poiCategory.getSelectedItem() + "'", null);
			}
			aPOIGeoPoint.clear();
			aPOIName.clear();
			aPOICategory.clear();
			aPOIArray.clear();
			aPOIID.clear();
			setResult(20001);
		}
	}
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == 30001){
			poiCategory.setSelection(CatetoryAdapter.getPosition("Imported"));
			buildPOIListView("Imported");
		}
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DeleteSelected:
            return new AlertDialog.Builder(this)
        	        	.setIcon(R.drawable.alert_dialog_icon)
        	        	.setTitle("Confirmation")
        	        	.setMessage("Are you sure to delete the selected POI?")
        	        	.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	            public void onClick(DialogInterface dialog, int whichButton) {
        	                /* User clicked OK so do some stuff */
        	            	DeletePOI(false);
        	            	}
        	        	})
        	        	.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	            public void onClick(DialogInterface dialog, int whichButton) {
        	
        	                /* User clicked Cancel so do some stuff */
        	            	}
        	        	})
        	        	.create();
        case DIALOG_DeleteCategory:
            return new AlertDialog.Builder(this)
        	        	.setIcon(R.drawable.alert_dialog_icon)
        	        	.setTitle("Confirmation")
        	        	.setMessage("Are you sure to delete all POI in this category?")
        	        	.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	            public void onClick(DialogInterface dialog, int whichButton) {
        	                /* User clicked OK so do some stuff */
        	            	DeletePOI(true);
        	            	}
        	        	})
        	        	.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	            public void onClick(DialogInterface dialog, int whichButton) {
        	
        	                /* User clicked Cancel so do some stuff */
        	            	}
        	        	})
        	        	.create();            
        case DIALOG_DeleteAll:
            return new AlertDialog.Builder(this)
        	        	.setIcon(R.drawable.alert_delete_icon)
        	        	.setTitle("Confirmation")
        	        	.setMessage("Are you sure to delete ALL POI?")
        	        	.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	            public void onClick(DialogInterface dialog, int whichButton) {
        	                /* User clicked OK so do some stuff */
        	            	DeletePOI(true);
        	            	}
        	        	})
        	        	.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	            public void onClick(DialogInterface dialog, int whichButton) {
        	
        	                /* User clicked Cancel so do some stuff */
        	            	}
        	        	})
        	        	.create();
        case DIALOG_CategoryList:
            return new AlertDialog.Builder(this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle("Choose a new Category")
                .setSingleChoiceItems(R.array.poi_category, 0, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        /* User clicked on a radio button do some stuff */
                    	String[] items = getResources().getStringArray(R.array.poi_category);
                    	SetNewCategory(items[whichButton]);
                    }
                })
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	/* User clicked so do some stuff */
                    	ChangeCategory(newCategory);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked No so do some stuff */
                    }
                })
               .create();

            
        }
        return null;
    }

    private void showEditPOIDialog(final Context context, final String ID, final String Name, 
    		String Category, final Integer RecordPos) {
		View v = View.inflate(context, R.layout.editpoi , null);
		final AlertDialog dialog = new AlertDialog.Builder(context).create();
		dialog.setView(v);
		
		String sDescription = "";
		boolean bHide = false;
		final Cursor c;
		c = this.mPOI.rawQuery("Select description,show from PlacesInfo where " +
				"name = '"+ Name.replace("'", "''") +"' and category = '" + Category + "'", null);
				//"name = '"+ Name.replace("'", "''") +"' ", null);
		if (c.moveToFirst()) {
			sDescription = c.getString(0);
			bHide = c.getInt(1) == 1 ? false : true ;
		}
		c.close();
		//set title
		dialog.setTitle(R.string.edit_poi_title_update);

		//set name & description
		final EditText nameValue = (EditText) v.findViewById(R.id.nameValue);
		nameValue.setText(Name);
		final EditText descriptionValue = (EditText) v.findViewById(R.id.descriptionValue);
		descriptionValue.setText(sDescription);
		// set city
		final EditText cityValue = (EditText) v.findViewById(R.id.cityValue);
		cityValue.setVisibility(View.GONE);
		
		//set poi category
		final Spinner poiCategory = (Spinner) v.findViewById(R.id.poicategory);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.poi_category,
                android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        poiCategory.setAdapter(adapter);
        poiCategory.setSelection(adapter.getPosition(Category));
       	poiCategory.setFocusableInTouchMode(true);
       	poiCategory.requestFocus();

		final TextView validationError = (TextView) v.findViewById(R.id.validationError); 
		
		//set delete check box
		final CheckBox ckbDelete = (CheckBox) v.findViewById(R.id.CKBDelete);
		ckbDelete.setChecked(false);
		ckbDelete.setVisibility(View.VISIBLE);
		final CheckBox ckbHide = (CheckBox) v.findViewById(R.id.CKBHide);
		ckbHide.setChecked(bHide);
		ckbHide.setVisibility(View.VISIBLE);
		
		
		final Button cancelBtn = (Button) v.findViewById(R.id.cancelBtn);
		cancelBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
		final Button addBtn = (Button) v.findViewById(R.id.addBtn);
		addBtn.setText("Update");

		addBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				String name = nameValue.getText().toString();
				boolean SkipDuplicateCheck = name.equalsIgnoreCase(Name);
				String description = descriptionValue.getText().toString();
				if(name.trim().length() ==0){
					validationError.setText(R.string.EMPTY_NAME_ERROR);
				}else {
					if (addBtn.getText()== "Update"){ //update an existed POI
						if (ckbDelete.isChecked()){
							DeletePOI(ID,RecordPos);
							dialog.dismiss();
						}else {
							if (setPOI(ID, name,description,(String)poiCategory.getSelectedItem(),
									"Default", ckbHide.isChecked()? "0" : "1", SkipDuplicateCheck, RecordPos) == 1 ){
								validationError.setText("Duplicate POI, please change the Name.");
								//Toast.makeText(MainView.this, "Duplicate POI found, please change the Name.", Toast.LENGTH_SHORT).show();
							}
							else
								dialog.dismiss();
						}
					}
				}
			}
		});
		
		final Button gotoBtn = (Button) v.findViewById(R.id.gotoBtn);
		gotoBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				setResult(20003,new Intent(aPOIGeoPoint.get(RecordPos)));
				dialog.dismiss();
				finish();
			}
		});

		dialog.setCancelable(true);
		dialog.show();
	}
    
    private Integer setPOI(String ID, String aName, String aDescription,String Category, String City, 
    		String Show, boolean SkipDuplicateCheck, Integer RecordPos)
	{
		aName = aName.replaceAll("'", "''");
		aDescription = aDescription.replaceAll("'", "''");
		//Toast.makeText(this, "X:"+Integer.toString(Latitude)+"|Y:"+Integer.toString(Longitude), 4000);
		if (!SkipDuplicateCheck){
			final Cursor c = this.mPOI.rawQuery("Select * from PlacesInfo where name = '" + aName + 
					"' and category = '" + Category	+ "' and city = '" + City + "'", null);
			if (c.getCount()>0){
				c.close();
				return 1; // there is already a POI with same key exist
			}
			c.close();
		}
		this.mPOI.execSQL("Update PlacesInfo set name = '" + aName + "', category = '" + Category	+ "', city = '" + City + "', " +
				"description = '" + aDescription + "', show = " + Show + " where PlaceID = "+ ID +";");
		aPOIName.set(RecordPos, aName);
		aPOICategory.set(RecordPos, Category);
		aPOIArray.notifyDataSetChanged();
		return 0;
	}
}
